from fastapi import FastAPI
from afast_core.core_plugins.pluginbase import IBasePlugin as BasePlugin
from pydantic import BaseSettings as Settings
from afast_core.core_libs.redis.aioredis import AsyncRedisClient


class ASyncAioRedisPluginClient(AsyncRedisClient, BasePlugin):

    '''
    使用示例：
    ASyncAioRedisPluginClient(core_app=core_app, configs=ASyncAioRedisPluginClient.RedisSettings(
        #   redis://[[username]:[password]]@localhost:6379/0
        #   rediss://[[username]:[password]]@localhost:6379/0
        #   unix://[[username]:[password]]@/path/to/socket.sock?databases=0
        from_url= "redis://127.0.0.1:6379/0"
    ))
    '''

    # 设置插件默认的参数信息
    name = 'ASyncAioRedis'

    class RedisSettings(Settings):
        from_url:str
        # 声明redis连接池的decode_responses字段来对键值对进行默认编码
        # 一般情况下，如果redis只存储一些str字符串等键值对，推荐使用decode_responses来避免在代码手动decode -- decode_responses:bool = True
        # 如果存贮的内容涉及：涉及对象，字典，列表等的存储，不使用decode_responses -- decode_responses:bool = False
        decode_responses: bool = False
        encoding = "utf-8"

    def setup(self, app: FastAPI, name: str = None, *args, **kwargs):
        """插件初始化"""
        self.app = app
        self._async_aioredis = None

        @app.on_event("startup")
        async def startup_event():
            self._async_aioredis = await self.init_aioredis_pool(setting=self.settings)
            await self._async_aioredis.set("test2", 'ASyncAioRedisPluginClient')
            print('test2',await self._async_aioredis.get("test2"))
            app.async_aioredis = self._async_aioredis

        @app.on_event("shutdown")
        async def shutdown_event():
            if self._async_aioredis:
                await self._async_aioredis.close()
